package edu.fanhuiling.blogsystem.config;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import edu.fanhuiling.blogsystem.model.Result;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;
@ControllerAdvice
//统一返回结果
public class ResponseAdvice implements ResponseBodyAdvice {
    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        return true;//true表示统一结果才生效
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        //如果返回的已经是Result类型了，直接返回body
        if (body instanceof Result){
            return body;
        }
        //如果返回的类型是String 类型，需要转换格式【在源码中Result转String出
        // 错，所以需要对String为返回类型的方法做处理——————转成String类型】
        if (body instanceof  String){
            ObjectMapper objectMapper=new ObjectMapper();
            try {
                return objectMapper.writeValueAsString(Result.success(body));
            } catch (JsonProcessingException e) {
                throw new RuntimeException(e);
            }

        }
        return Result.success(body);//将body放在Result中进行统一返回结果
    }
}
